package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: Daisen.Z
 * @Date: 2021/12/16 16:31
 * @Version: 1.0
 * @Description:
 */
@RestController
@Slf4j
public class PaymentController {
    @Autowired
    private PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/create")
    public CommonResult create(@RequestBody Payment payment){
        int result = paymentService.create(payment);
        log.info("***********插入结果："+result);
        if (result > 0){
            return new CommonResult(200,"成功serverPort:"+serverPort,result);
        }else {
            return new CommonResult(444,"失败",result);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        Payment payment = paymentService.getPaymentById(id);
        log.info("***********查询结果："+payment+"😄");
        if (payment != null){
            return new CommonResult(200,"查询成功,serverPort:"+serverPort,payment);
        }else {
            return new CommonResult(444,"查询失败",payment);
        }
    }

    // 服务发现测试
    @GetMapping("/payment/discovery")
    public Object getPaymentById(){
        // 获取所有的服务名称
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            // 打印服务信息
            log.info("*********service:"+service);
        }

        // 获取CLOUD-PAYMENT-SERVICE服务下的所有实例（8001，8002）
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            // 打印服务名下的所有实例信息
            log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
        }

        // 返回discoveryClient，看下他都具备哪些信息
        return this.discoveryClient;
    }
}
